package shop

import (
	"encoding/json"
	"yixiang.co/yshop/controllers"
	"yixiang.co/yshop/models"
	"yixiang.co/yshop/models/dto"
	"yixiang.co/yshop/models/vo"
)

// 商品 api
type StoreProductController struct {
	controllers.BaseController
}

func (c *StoreProductController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
}

// @Title 商品列表
// @Description 商品列表
// @Success 200 {object} controllers.Result
// @router / [get]
func (c *StoreProductController) GetAll() {
	enabled, _ := c.GetInt("isShow", -1)
	total, list := models.GetAllProduct(c.GetParams(), enabled)
	mapList := models.GetProductCate()
	c.Ok(vo.ResultList{Content: list, TotalElements: total, ExtendData: mapList})
}

// @Title 获取商品信息
// @Description 获取商品信息
// @Success 200 {object} controllers.Result
// @router /info/:id [get]
func (c *StoreProductController) GetInfo() {
	id, _ := c.GetInt64(":id", 0)
	c.Ok(models.GetProductInfo(id))
}

// @Title 商品添加
// @Description 商品添加
// @Success 200 {object} controllers.Result
// @router /addOrSave [post]
func (c *StoreProductController) Post() {
	var (
		dto dto.StoreProduct
		e   error
	)
	json.Unmarshal(c.Ctx.Input.RequestBody, &dto)
	c.Valid(&dto)

	//logs.Info(dto)
	_, e = models.AddOrSaveProduct(&dto)

	if e != nil {
		c.Fail("添加产品失败", 5002)
	}
	c.Ok("操作成功")
}

// @Title 商品上下架
// @Description 商品上下架
// @Success 200 {object} controllers.Result
// @router /onsale/:id [post]
func (c *StoreProductController) OnSale() {
	var dto dto.OnSale
	id, _ := c.GetInt64(":id", 0)
	json.Unmarshal(c.Ctx.Input.RequestBody, &dto)
	e := models.OnSaleByProduct(id,dto.Status)
	if e != nil {
		c.Fail(e.Error(), 5004)
	}
	c.Ok("操作成功")
}

// @Title 商品删除
// @Description 商品删除
// @Success 200 {object} controllers.Result
// @router /:id [delete]
func (c *StoreProductController) Delete() {
	var ids []int64
	id, _ := c.GetInt64(":id",1)
	ids = append(ids, id)
	e := models.DelByProduct(ids)
	if e != nil {
		c.Fail(e.Error(), 5005)
	}
	c.Ok("操作成功")
}

// @Title 商品sku生成
// @Description 商品sku生成
// @Success 200 {object} controllers.Result
// @router /isFormatAttr/:id [post]
func (c *StoreProductController) FormatAttr() {
	id, _ := c.GetInt64(":id", 0)
	var (
		jsonObj map[string]interface{}
	)
	json.Unmarshal(c.Ctx.Input.RequestBody, &jsonObj)

	res := models.GetFormatAttr(id, jsonObj)
	c.Ok(res)
}
